import {createRouter, createWebHashHistory, RouteRecordRaw} from 'vue-router';
import {App} from "vue";
import Cookies from "js-cookie";
import store from '../store';
import {getAdminInfoApi} from "../request/api";
import component from "*.vue";

// import Vue from 'vue';
// Vue.use(VueRouter)
// Vue2.use : 调用的就是参数上的install方法，或者是直接调用参数，

const routes: RouteRecordRaw[] = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/login/index.vue')
    },
    /*{
        path: '/homepage',
        name: 'homepage',
        component: () => import('../views/homepage/homepage.vue')
    }*//*,
    {
        path: '/pms',
        name: 'pms',
        component: () => import('../views/homepage/homepage.vue'),
        children: [
            {
                path: 'product',
                name: 'product',
                component: () => import('../views/pms/product.vue')
            }
        ]
    }*/
]

const router = createRouter({
    history: createWebHashHistory(),
    routes // 路由配置
})

// 根据getters里菜单对象生成路由规则
const genRouter = () => {
    const menus = store.getters.getAdminInfo.menus;
    console.log(menus)
    // 循环菜单对象
    for (let menusKey in menus) {
        const newRouter: RouteRecordRaw = {
            path: '/' + menus[menusKey].name,
            name: menus[menusKey].name,
            meta: {
                title: menus[menusKey].title,
            },
            component: () => import('../views/homepage/homepage.vue'),
            redirect: '/' + menus[menusKey].name + '/' + menus[menusKey].children[0].name + '/' + menus[menusKey].children[0].name,
            children: []
        };
        for (let i = 0; i < menus[menusKey].children.length; i++) {
            newRouter.children?.push({
                path: menus[menusKey].children[i].name,
                name: menus[menusKey].children[i].name,
                meta: {
                    title: menus[menusKey].children[i].title,
                },
                component: () => import(`../views/${menus[menusKey].name}/${menus[menusKey].children[i].name}/${menus[menusKey].children[i].name}.vue`),
            })
        }
        router.addRoute(newRouter);
    }
    // 动态添加首页
    router.addRoute({
        path: '/',
        name: 'homepage',
        component: () => import('../views/homepage/homepage.vue'),
        // 重定向
        redirect: '/index',
        children: [{
            path: '/index',
            name: 'index',
            component: () => import('../views/index/index.vue'),
        }]
    });
}

// 前置导航守卫
router.beforeEach((to, from, next) => {
    // 1.token && vuex里面menus（权限列表）为空
    const token = Cookies.get("token");
    if (store.state.adminInfo.menus.length === 0 && token) {
        // 异步
        store.dispatch('getAdminInfo').then(res => {
            genRouter()
            next(to.path);
        });
    } else if (token && store.state.adminInfo.menus.length !== 0 && from.path === '/login' && to.path === '/homepage') {
        genRouter()
        next('/index');
    } else if (!token && to.path !== '/login') {
        next('/login');
    } else if (token && to.path === '/login') {
        next(from);
    } else {
        next();
    }

})

export const initRouter = (app: App<Element>) => {
    app.use(router)
}
